package com.naiterui.ehp.bs.wechat.service.impl;

import com.naiterui.ehp.bs.wechat.param.custom.BaseCustomParam;
import com.naiterui.ehp.bs.wechat.param.custom.MiniProgramMsgParam;
import com.naiterui.ehp.bs.wechat.param.custom.TextMsgParam;
import com.naiterui.ehp.bs.wechat.protocol.msg.custom.CustomMsg;
import com.naiterui.ehp.bs.wechat.service.IAccessTokenService;
import com.naiterui.ehp.bs.wechat.service.ICustomMsgApiService;
import com.naiterui.ehp.bs.wechat.utils.WeChatApiUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * @author zhoupeipei
 * @date 2019-06-18 15:42
 * @since 1.0.0
 */
@Service
public class CustomMsgApiServiceImpl implements ICustomMsgApiService {
    private static final Logger LOGGER = LoggerFactory.getLogger(CustomMsgApiServiceImpl.class);
    @Autowired
    IAccessTokenService accessTokenService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void sendSystemMsg(String openId, String content) {
        if (StringUtils.isEmpty(openId) || StringUtils.isEmpty(content)) {
            LOGGER.error("系统客服消息发送参数异常，openId{};content:{}", openId, content);
        }
        TextMsgParam textMsgParam = new TextMsgParam(openId, content);
        sendCustomMsg(textMsgParam);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void sendCustomMsg(BaseCustomParam customMsgParam) {
        CustomMsg customMsg = Optional.ofNullable(customMsgParam).
                map(customParam -> customParam.getCustomProtocol()).orElse(null);
        Optional.ofNullable(customMsg)
                .ifPresent(msg -> WeChatApiUtil.sendCustomMsg(accessTokenService.accessToken(), msg));

    }

    @Override
    public void sendMiniProgramMsg(String openId, String title, String appId, String pagePath, String thumbMediaId) {
        if (StringUtils.isEmpty(openId)
                || StringUtils.isEmpty(title)
                || StringUtils.isEmpty(appId)
                || StringUtils.isEmpty(pagePath)
                || StringUtils.isEmpty(thumbMediaId)) {
            LOGGER.error("系统客服消息发送参数异常，openId{};content:{};title:{};appId:{};pagePath:{};thumbMediaId:{}", openId, title, appId, pagePath, thumbMediaId);
        }
        MiniProgramMsgParam miniProgramMsgParam = new MiniProgramMsgParam(openId, title, appId, pagePath, thumbMediaId);
        sendCustomMsg(miniProgramMsgParam);
    }
}
